const {
  apiUrl,
  storageKey
} = require("./../config/config");

let isLoginTip=false //是否登录提示

function pureGet(url) {
  let promise = new Promise(function (resolve, reject) {
    wx.request({
      url: apiUrl + url,
      method: "GET",
      success: function (res) {
        resolve(res.data);
      },
      fail: reject,
    });
  });

  return promise;
}

function fun(url, method, data, header) {
  data = data || {};
  let token = wx.getStorageSync('token');
  header = header || {
    'Content-Type': 'application/json',
  };
  if (token) {
    header['X-Access-Token'] = token
  }
  wx.showNavigationBarLoading();
  const _this = this
  let promise = new Promise(function (resolve, reject) {
    wx.request({
      url: apiUrl + url,
      header: header,
      data: data,
      method: method,
      timeout: 100000,
      success: function (res) {
        if (typeof res.data === "object") {
          if (res.statusCode === 200) {
            getApp().globalData.loader = false
            if (res.data.code === -1) {
              reject(res.data);
            } else {
              if (res.data.code === 200) {
                try {
                  const data = res.data.result ? res.data.result : res.data.success;
                  resolve(res.data);
                } catch (err) {
                  resolve(res.data);
                }
              } else if (res.data.code === 500) {
                if(url=='api/user/school/recommend')return
                var msg = res.data.message ? res.data.message : '请求失败'
                if (msg == '请先开通VIP') {
                  resolve({
                    msg: msg,
                    result: false
                  })
                } else {
                  wx.showToast({
                    title: msg,
                    icon: 'none'
                  })
                }
              }else if(res.data.code === 404){
                var msg = res.data.message ? res.data.message : '请求失败'
                wx.showToast({
                  title: msg,
                  icon: 'error'
                })
              }
            }
          } else if (res.statusCode === 500) {
            wx.hideLoading()
            reject(res.data);
            console.log(res.data)
            wx.removeStorageSync('token')
            let currentPages = getCurrentPages();
            let _this = currentPages[currentPages.length - 1];
            if(url=='api/user')return;
            // if(['pages/major/index/index','pages/major/detail/index','pages/optional/index/index'].includes(_this.route))return;
            if(!isLoginTip){
              isLoginTip=true
              wx.showModal({
                title: '是否跳转至登录页',
                content: '需要您登录后，才能获取其中的内容',
                success: function (res) {
                  isLoginTip=false
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '/pages/login/index',
                    })
                  }
                }
              })
            }
          }

        }
      },
      fail: function (err) {
        reject(err)
      },
      complete: function () {
        wx.hideNavigationBarLoading();
      }
    });

  });
  return promise;
}



function getToken() {
  let promise = new Promise(function (resolve, reject) {
    wx.request({
      url: apiUrl + '/mp/qiniu/upload/token',
      header: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImI1YzAwOTcxLTUxMzEtNDM0Yy05MTA1LWY1NmE0ZmM1Mjg2MiJ9.dLsCjjhw8-jY_PV9_e9CMD5VwbGYbNAInvS1BT-3ql3BdHpt4_ijIRGkv9YWin0AXgWmU3GlLeOP_9xVwUVbLA'
      },
      method: 'get',
      success: function (res) {
        const data = res.data.data
        resolve(data);
      },
      fail: function (err) {
        reject(err)
      },
      complete: function () {
        wx.hideNavigationBarLoading();
      }
    });
  })
  return promise
}

function upload(url, name, filePath) {
  let header = {};
  let sessionId = wx.getStorageSync(storageKey.sessionId); //从缓存中拿该信息
  if (sessionId) {
    if (!header || !header["Authorization"]) {
      header["Authorization"] = sessionId; //添加到请求头中

    }
  }

  wx.showNavigationBarLoading();
  let promise = new Promise(function (resolve, reject) {
    wx.uploadFile({
      url: apiUrl + url,
      filePath: filePath,
      name: name,
      header: header,
      success: function (res) {
        resolve(res);
      },
      fail: function (err) {
        wx.hideLoading()

        reject(err)
      },
      complete: function () {
        wx.hideNavigationBarLoading();
      }
    });
  });
  return promise;
}

module.exports = {
  "pureGet": (url) => {
    return pureGet(url)
  },
  "get": function (url, data, header) {
    return fun(url, "GET", data, header);
  },
  "post": function (url, data, header) {
    return fun(url, "POST", data, header);
  },
  "Delete": function (url, data, header) {
    return fun(url, "DELETE", data, header);
  },
  "Put": function (url, data, header) {
    return fun(url, "PUT", data, header);
  },
  upload: function (url, name, filePath) {
    return upload(url, name, filePath);
  },
  getToken,
};
